<template>
    <div class="add_goods">
      <!-- 面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片试图 -->
      <el-card class="box-card">
        <!-- 警告区域 -->
        <el-alert
          title="添加商品信息"
          type="info"
          center
          :closable="false"
          show-icon>
        </el-alert>
        <!-- 步骤条 -->
        <el-steps :active="activeIndex-0" align-center finish-status="success">
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
        <!-- tabs页签 -->
        <el-form ref="addGoodsForm" label-position="top" :rules="addGoodsRules" :model="addGoodsForm" label-width="80px">
          <el-tabs @tab-click="tabsClick()" :before-leave="beforeLeaveTabs" tab-position="left" v-model="activeIndex">
            <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="addGoodsForm.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price">
                <el-input type="number" v-model="addGoodsForm.goods_price"></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight">
                <el-input  type="number" v-model="addGoodsForm.goods_weight"></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input type="number" v-model="addGoodsForm.goods_number"></el-input>
              </el-form-item>
              <el-form-item label="商品分类" prop="goods_number">
                <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="cateList"
                :props="cascaderProps"
                @change="handleChange">
                </el-cascader>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品参数" name="1">
              <el-form-item :label="item.attr_name" v-for="item in manyData" :key="item.attr_id">
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox 
                  border
                  :label="item" 
                  v-for="(item,index) in item.attr_vals"
                  :key="index">
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品属性" name="2">
              <el-form-item :label="item.attr_name" v-for="item in onlyData" :key="item.attr_id">
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name="3">
              <el-upload
                class="upload-demo"
                action="http://127.0.0.1:8888/api/private/v1/upload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :headers="headersObj"
                :on-success="imgUploadSuccess"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name="4">
              <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
              <el-button @click="addGoods()" type="primary" class="addBtn">添加商品</el-button>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </el-card>
      <!-- 预览图片对话框 -->
      <el-dialog :visible.sync="previewImgDialogvisible" width="50%">
        <img style="width: 100%;" :src="img_url" />
      </el-dialog>
    </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      activeIndex: '0',
      // 添加商品表单
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [1,3,6],
        // 商品图片
        pics: [
        ],
        // 编辑内容
        goods_introduce: '',
        attrs: []
      },
      // 校验商品表单的规则
      addGoodsRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ]
      },
      // 分类数据
      cateList: [],
      // 级联选择器配置对象
      cascaderProps:{ 
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id'
      },
      // 动态参数
      manyData: [],
      // 静态属性
      onlyData: [],
      // 配置上传图片的请求头
      headersObj: {
        Authorization: sessionStorage.getItem('token')
      },
      // 控制显示预览图片对话框
      previewImgDialogvisible: false,
      // 预览图片的url
      img_url: ''
    }
  },

  created() {
    this.getCateList()
  },

  methods: {
    // 获取商品分类数据   今天完成了
    async getCateList () {
      const {data: res} = await this.$axios.get('categories')
      if(res.meta.status !== 200) return this.$message.error('获取失败')
      this.cateList = res.data
    },
    // 级联选择发生变化
    handleChange () {
      if(this.addGoodsForm.goods_cat.length !== 3){
        return this.addGoodsForm.goods_cat = []
      }
      console.log(this.addGoodsForm.goods_cat)
    },
    // tabs页签离开某一项之前
    beforeLeaveTabs (n,o) {
      // 需要知道什么时候离开的是基本信息？
      // 如果o === '0'
      // this.addGoodsForm.goods_cat.length === 3
      if(o === '0' && this.addGoodsForm.goods_cat.length !== 3){
        this.$message.error('请选择三级商品分类')
        return false 
      }
      return true
    },
    // 点击tabs标签页
    async tabsClick () {
      if(this.activeIndex === '1') {
        // 代表进入了商品参数
        const {data: res} = await this.$axios.get(`categories/${this.addGoodsForm.goods_cat[2]}/attributes`,{
          params:{
            sel: 'many'
          }
        })
        res.data.forEach(item=>{
          item.attr_vals = item.attr_vals=== ''?[]:item.attr_vals.split(' ')
        })
        if(res.meta.status !== 200) return this.$message.error('获取数据失败')
        this.manyData = res.data
      }else if(this.activeIndex === '2') {
        // 代表进入了商品属性
        const {data: res} = await this.$axios.get(`categories/${this.addGoodsForm.goods_cat[2]}/attributes`,{
          params:{
            sel: 'only'
          }
        })
        if(res.meta.status !== 200) return this.$message.error('获取数据失败')
        this.onlyData = res.data
      }
    },
    // 预览图片
    handlePreview (files) {
      this.previewImgDialogvisible = true
      this.img_url = files.response.data.url
    },
    // 删除图片
    handleRemove (files) {
      const tmp_path = files.response.data.tmp_path
      const index = this.addGoodsForm.pics.findIndex(item=>{
        return item.pic === tmp_path
      })
      this.addGoodsForm.pics.splice(index,1)
    },
    // 图片上传成功
    imgUploadSuccess (res) {
      if(res.meta.status !== 200) return this.$message.error('上传失败')
      this.addGoodsForm.pics.push({
        pic: res.data.tmp_path
      })
    },
    // 添加商品
    addGoods () {
      this.$refs.addGoodsForm.validate(async flag=>{
        if(!flag) return this.$message.error('亲，请填写必填项呦！')
        // const form = JSON.parse(JSON.stringify(this.addGoodsForm))
        // console.log('表单合法',form===this.addGoodsForm)
        // 整理 attrs
        this.manyData.forEach(item=>{
          this.addGoodsForm.attrs.push({
            "attr_id":item.attr_id,
            "attr_value": item.attr_vals.join(' ')
          })
        })
        this.onlyData.forEach(item=>{
          this.addGoodsForm.attrs.push({
            "attr_id":item.attr_id,
            "attr_value": item.attr_vals
          })
        })
        const form = _.cloneDeep(this.addGoodsForm)
        form.goods_cat = form.goods_cat.join(',')
        const { data: res } = await this.$axios.post('goods',form)
        if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success('创建成功')
        this.$router.push('/goods')
      })
    }
  }
};
</script>

<style scoped lang='less'>
.el-checkbox {
  margin-right: 0px;
}
.addBtn {
  margin: 15px 0;
}
</style>
